<template>
  <view class="page_root" data-page-name="工单列表" data-page-identification="w_m92anenduc">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_i5ppazsnoy 自定义模板_5oukehelx5 -->

    <view class="gdlb-body">
      <!-- 筛选 -->
      <u-popup
        mode="top"
        width="100%"
        v-model="state.filterShow"
        :is-fixed="true"
        height="80%"
        border-radius="32"
      >
        <view class="filter-wrapper">
          <u-navbar
            title="工单列表"
            back-icon-color="#fff"
            title-color="#fff"
            :border-bottom="false"
            :custom-back="navbarBackFn"
          >
          </u-navbar>
          <!-- 滚动主体区域 -->
          <scroll-view class="form-body" scroll-y>
            <!-- 工单标题 -->
            <u-input
              v-model:modelValue="state.filter.keyWords"
              placeholder="请输入工单标题"
              clearable="true"
              border
            ></u-input>

            <view v-for="(group, gIndex) in filterGroups" :key="group.key" class="filter-group">
              <view class="filter-header">
                <text class="title">{{ group.label }}</text>
                <text
                  v-if="group.options.length > maxVisible"
                  class="toggle"
                  @click="group.expanded = !group.expanded"
                >
                  {{ group.expanded ? '收起' : '展开' }}
                </text>
              </view>

              <view
                class="tag-list"
                :class="{ collapsed: !group.expanded && group.options.length > maxVisible }"
              >
                <view
                  v-for="opt in group.options"
                  :key="opt.value"
                  class="tag"
                  :class="{ active: group.selected === opt.value }"
                  @click="toggleTag(group, opt)"
                >
                  {{ opt.label }}
                </view>
              </view>
            </view>
          </scroll-view>
          <!-- 底部操作栏 -->
          <view class="footer-bar">
            <van-button type="default" size="small" @click="resetData">取消</van-button>
            <van-button
              type="primary"
              size="small"
              :loading="state.fatherLoading"
              @click="
                () => {
                  handleFilterChange();
                  state.filterShow = false;
                }
              "
            >
              确定
            </van-button>
          </view>
        </view>
      </u-popup>

      <!-- 筛选 -->
      <u-mask :show="state.loading">
        <view class="warp">
          <view class="rect" @tap.stop>加载中....</view>
        </view>
      </u-mask>
      <u-navbar back-icon-color="#fff" title="工单列表" title-color="#fff" :border-bottom="false">
        <template #right>
          <view class="right-icon" @click="handleShowAddOrEdit({})"></view>
        </template>
      </u-navbar>
      <view class="fixed-filter">
        <van-config-provider :theme-vars="themeVars">
          <view class="filters-row">
            <!-- 左侧两项：作为一组靠左显示 -->
            <view class="left-group">
              <view class="dropdown-card">
                <van-dropdown-menu>
                  <van-dropdown-item
                    v-model="state.filter.createdByName"
                    :title="getCreateTitle"
                    :options="userOptions"
                    @change="handleFilterChange"
                  />
                </van-dropdown-menu>
              </view>

              <view class="dropdown-card">
                <van-dropdown-menu>
                  <van-dropdown-item
                    v-model="state.filter.solverName"
                    :title="getSolverTitle"
                    :options="userOptions"
                    @change="handleFilterChange"
                  />
                </van-dropdown-menu>
              </view>
            </view>

            <!-- 右侧“更多”：靠最右显示 -->
            <view class="right-group" @click="state.filterShow = true">
              <view class="dropdown-card more-card"><view class="seatch-icon"></view> 筛选 </view>
            </view>
          </view>
        </van-config-provider>
      </view>
      <scroll-view scroll-y="false" class="main" @scrolltolower="handleScrollToLower">
        <view class="gd-item" v-for="(item, index) in state.dataList" :key="item.id">
          <view class="gd-content">
            <view class="gd-top-icon">
              <view class="title-left-icon">
                <view
                  class="proority-view"
                  :style="{
                    backgroundColor: getPriorityType(item.priority),
                  }"
                >
                  {{ priorityMap[item.priority] }}
                </view>
                <view class="gd-type">{{ item.type }}</view>
              </view>

              <view class="title-right-icon">
                <view class="time-out" v-if="item.timeout === '是'">已超时</view>
                <view class="status-view" :style="getColorStyle(item.status)">{{
                  item.status
                }}</view>
              </view>
            </view>
            <view class="gd-title" @tap="jumpDetail(item.id)">{{ item.content }}</view>
            <view class="gd-msg first-line">
              <view class="msg-item">
                <van-icon size="28rpx" name="user-circle-o" color="rgba(0, 0, 0, 0.45)" />
                <view class="default-font">创建人:</view>
                <view class="bold-font">{{ item.createdBy }}</view>
              </view>
              <view class="msg-item">
                <van-icon name="location-o" size="28rpx" color="rgba(0, 0, 0, 0.45)" />
                <view class="default-font">区域:</view>
                <view class="bold-font">{{ item.areaName }}</view>
              </view>
            </view>
            <view class="gd-msg second-line">
              <view class="msg-item">
                <van-icon size="28rpx" color="rgba(0, 0, 0, 0.45)" name="user-o" />
                <view class="default-font">解决人:</view>
                <view class="bold-font">{{ item.solver }}</view>
              </view>
              <view class="msg-item">
                <van-icon name="friends-o" size="28rpx" color="rgba(0, 0, 0, 0.45)" />
                <view class="default-font">客户:</view>
                <view class="bold-font">{{ item.customer }}</view>
              </view>
            </view>
            <u-line color="#D9D9D9" class="third-line" margin="0 24rpx 18rpx 24rpx" />
            <OperationButton :operationForm="item" @refresh="() => getData(true)" />
          </view>

          <!-- <view class="operatin-btn">
          <OperationButton :operationForm="item" @refresh="() => getData(true)"
        /></view> -->
        </view>
      </scroll-view>
    </view>
    <!-- end vid_i5ppazsnoy 自定义模板_5oukehelx5 -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    // getApplicationId,
    // getComponentParamsValue,
    // get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  // import {
  //   propertyFormatByNumber,
  //   propertyFormatByPercentage,
  //   propertyFormatByDate,
  //   parseSubFromDataList,
  // } from '@/utils/format';
  // import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  import { handleRedirect } from '@/utils/common';
  import {
    onPullDownRefresh,
    onLoad,
    onReady,
    onShow,
    onHide,
    onPageScroll,
    onUnload,
  } from '@dcloudio/uni-app';
  /*** UNI_APP_EXEGESIS ***
    import { handleRedirect, permission, parseJson } from '@/utils/common';
    import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
    import { BroadcastMessage } from '@/utils/BroadcastMessage';
    import { sendToken } from "@/hooks/useIframeToken";
    *** UNI_APP_EXEGESIS ***/

  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000001010';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {};

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_i5ppazsnoy_props = reactive({
    code: '',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_5oukehelx5 ref 的引用
  const vid_i5ppazsnoy_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_i5ppazsnoy_ref };

  const showState = reactive({
    vid_i5ppazsnoy_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_a0lx68gn8e = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
        // 获取上一层传递的数据
        const workflowChannel = new BroadcastMessage('WORKFLOW');
        workflowChannel.publish({ status: 'Ready' });
        workflowChannel.subscribe((data) => {
          if (data) {
            isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
          }
        });
        *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
    const routeOption = ref({})
    onLoad((option) => {
      routeOption.value = option;
    });
    onReady(() => {
      setPageParams(routeOption.value)
      // 设置表单的rule
      try{
  
      }catch{
          // do nothing
      }
    });
    // 图表刷新标记
    const uChartsReshowFlag = ref(false);
    onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
        uChartsReshowFlag.value = false
    })
    onShow(() => {
        uChartsReshowFlag.value = true; // 页面激活后,标记置为true
  
        setPageParams(routeOption.value)
    })
    onPageScroll(e => {
        pageScrollTop.value = e.scrollTop
    });
    *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
    onPullDownRefresh(() => {
      // 下拉刷新
      setTimeout(() => {
          uni.stopPullDownRefresh()
      }, 1000)
    })
    *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================

  const themeVars = reactive({
    // 'dropdown-menu-background-color': 'transparent', // 让背景透明以便自定义
    // 'dropdown-menu-box-shadow': 'none',
    // 'van-dropdown-menu-title-padding':'20rpx'
  });
  import AddOrEditWorkOrder from '../Page3000001236/Page3000001236.vue';
  import OperationButton from '../Page3000001237/Page3000001237.vue';
  // 按需导入 Vant 3 组件
  import {
    Form,
    Field,
    CellGroup,
    Picker,
    Popup,
    Uploader,
    Button,
    DatePicker,
    Toast,
    Col,
    Cell,
    Row,
    Icon,
    DropdownMenu,
    DropdownItem,
    ConfigProvider,
  } from 'vant';
  import 'vant/lib/index.css';
  import Quill from 'quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  import 'quill/dist/quill.snow.css';
  import { showToast, showFailToast, showSuccessToast } from 'vant';
  // 页面内注册 Vant 组件
  const { appContext } = getCurrentInstance();
  [
    ['van-form', Form],
    ['van-field', Field],
    ['van-cell-group', CellGroup],
    ['van-cell', Cell],
    ['van-picker', Picker],
    ['van-popup', Popup],
    ['van-uploader', Uploader],
    ['van-button', Button],
    ['van-date-picker', DatePicker],
    ['van-col', Col],
    ['van-row', Row],
    ['van-icon', Icon],
    ['van-config-provider', ConfigProvider],

    ['van-dropdown-menu', DropdownMenu],
    ['van-dropdown-item', DropdownItem],
  ].forEach(([name, comp]) => appContext.app.component(name, comp));
  const bgUrl = '';
  onMounted(() => {
    setPageStyle('gd-page');
    const queryString = window.location.search;

    // // 使用 URLSearchParams 解析参数字符串
    const urlParams = new URLSearchParams(queryString);

    // // 获取特定参数的值
    const key = urlParams.get('type');
    console.log(key, 'key');
    state.filter.mobileQuery = key;
    // 使用 URLSearchParams 解析参数字符串
    // const urlParams = new URLSearchParams(queryString);

    // 遍历参数并输出
    // urlParams.forEach((value, key) => {
    //   console.log(`${key}: ${value}`);
    // });
    getAllUser();
    getData(true);
    getWorkType();
    getWtly();
  });
  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  import { onReachBottom } from '@dcloudio/uni-app';
  import { nextTick } from 'vue';
  const state = reactive({
    filter: {
      // 工单类型
      type: undefined,
      // 优先级
      priority: undefined,
      // 工单状态
      status: '',
      // 问题来源
      questionSource: undefined,
      number: '',
      keyWords: '',
      solverName: undefined,
      createdByName: undefined,
    },
    filterShow: false,
    priorityList: [
      {
        label: 'p0',
        value: 'p0',
      },
      {
        label: 'p1',
        value: 'p1',
      },
      {
        label: 'p2',
        value: 'p2',
      },
      {
        label: 'p3',
        value: 'p3',
      },
    ],
    statusList: [
      {
        label: '全部工单',
        value: 'p0',
      },
      {
        label: '待分发',
        value: '待分发',
      },
      {
        label: '已关闭',
        value: '已关闭',
      },
      {
        label: '无需解决',
        value: '无需解决',
      },
      {
        label: '已解决',
        value: '已解决',
      },
      {
        label: '解决中',
        value: '解决中',
      },
      {
        label: '未开始',
        value: '未开始',
      },
      {
        label: '我的关注',
        value: '我的关注',
      },
    ],
    wtlyList: [],
    workTypeList: [],
    changeHaveSonStausList: [],
    dataList: [],
    collapseKey: [],
    allUser: [],
    allSearchUser: [],
    modalForm: {},
    modalTitle: '',
    userInfo: {},
  });

  const show = reactive({
    createdByName: false,
    solverName: false,
  });
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  function navbarBackFn() {
    state.filterShow = false;
  }
  //    新需求
  const newState = reactive({
    changeStatusLoading: false,
    isExpandAll: false,
    circulationVisible: false,
    resolvingVisible: false,
    resolvedVisible: false,
    circulationForm: {
      solverList: [],
      status: '流转',
    },
    resolvingForm: {
      solution: '',
      status: '解决中',
    },
    resolvedForm: {
      solution: '',
      attachmentList: [],
      status: '已解决',
      solutionDetail: '',
    },
    closeForm: {
      status: '关闭',
    },
    workOrderId: undefined,
  });
  onShow(() => {
    setTimeout(() => {
      getData(true); // 刷新数据
    }, 100);
  });

  function handleScrollToLower() {
    if (!state.loading) {
      getData(false); // 加载下一页
    }
  }
  const userOptions = computed(() => {
    return state.allSearchUser.map((item) => ({
      text: item.label,
      value: item.value,
    }));
  });
  const getCreateTitle = computed(() => {
    const value = state.filter.createdByName;
    const option = userOptions.value.find((item) => item.value === value);
    return option ? option.text : '创建人'; // 默认标题
  });
  const getSolverTitle = computed(() => {
    const value = state.filter.solverName;
    const option = userOptions.value.find((item) => item.value === value);
    return option ? option.text : '解决人'; // 默认标题
  });
  const moreDropdownRef = ref(null);
  async function handleFilterChange() {
    // 用户点了筛选后
    state.hasMore = true;
    state.loading = false;
    pagination.value.current = 1;
    getData(true);
  }
  const dataLoading = ref(false);
  async function getData(isRefresh = false) {
    state.loading = true;
    if (dataLoading.value) {
      state.loading = false; // 关闭 loading
      return;
    }

    if (isRefresh) {
      pagination.value.current = 1;
      state.dataList = [];
      state.hasMore = true;
    }

    if (!state.hasMore) {
      state.loading = false; // 关闭 loading
      return;
    }

    dataLoading.value = true;

    try {
      const data = await post('/solution-ppm-work-order/api/v1/work_order/search', {
        ...state.filter,
        pageSize: pagination.value.pageSize,
        pageNo: pagination.value.current,
      });

      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }

      const list = data.data.content || [];
      const total = data.data.totalElements || 0;

      // ✅ 拼接懒加载数据
      state.dataList = [...state.dataList, ...list];
      pagination.value.total = total;

      // ✅ 判断是否还有更多
      if (state.dataList.length >= total) {
        state.hasMore = false;
      } else {
        pagination.value.current++;
      }
    } finally {
      dataLoading.value = false;
      state.loading = false;
    }
  }

  function resetData() {
    state.filter = {
      // 工单类型
      type: undefined,
      // 优先级
      priority: undefined,
      // 工单状态
      status: '',
      // 问题来源
      questionSource: undefined,
      keyWords: undefined,
    };
    state.filterShow = false;
    pagination.value.current = 1;
    pagination.value.pageSize = 10;
    handleFilterChange();
  }
  const colorMap = {
    未开始: { color: '#fff', backgroundColor: '#A9A9A9 !important' },
    已解决: { color: '#fff', backgroundColor: '#52C41A !important' },
    解决中: { color: '#fff', backgroundColor: '#3875ff  !important' },
    无需解决: { color: '#fff', backgroundColor: '#FFC900  !important' },
    已关闭: { color: '#fff', backgroundColor: '#262626 !important' },
    已回访: { color: '#fff', backgroundColor: '#9254DE !important' },
    待分发: { color: '#fff', backgroundColor: '#FF7D27 !important' },
  };
  function getColorStyle(status) {
    return colorMap[status] || '#262626';
  }
  const editForm = ref({});
  const type = ref('add');
  function handleShowAddOrEdit(record) {
    console.log('到了');
    uni.removeStorageSync('edit_form'); // 防止上次的残留
    handleRedirect(`/pages/Page3000001236/Page3000001236?mode=add`);
    // editForm.value = record;
    // state.modalTitle = record.id ? '编辑工单' : '新建工单';
    // type.value = record.id ? 'edit' : 'add';
    // state.addOrEditVisible = true;
  }
  // 基础信息获取
  function getAllUser() {
    get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.allUser = data.data.userDtoList.map((item) => {
        return {
          label: item.name,
          value: item.name,
        };
      });
      state.allSearchUser = [{ label: '全部', value: '' }, ...state.allUser];
    });
  }
  // 问题来源
  // 获取问题来源
  function getWtly() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/GD.WTLY').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.wtlyList = data.data.map((item) => {
        return {
          label: item.itemName,
          value: item.itemName,
        };
      });
    });
  }
  // 获取工单类型字典值
  function getWorkType() {
    get(' /solution-ppm-basic-data/api/v1/dictionary/search/GD.GDLX').then((data) => {
      if (data.code !== 200) {
        showFailToast(data.message);
        return;
      }
      state.workTypeList = data.data.map((item) => {
        return {
          label: item.itemName,
          value: item.itemName,
        };
      });
    });
  }

  // Picker 确认事件
  function onConfirm(type, val) {
    // 普通 picker（非日期）
    if (['projectId', 'milepostId', 'taskId'].includes(type)) {
      const selected = val.selectedOptions?.[0];
      if (selected) {
        state.modalForm[`${type.replace('Id', '')}Name`] = selected.label; // 中文展示名
        state.modalForm[type] = selected.value; // 真正的 id
      }
    } else {
      state.filter[type] = val.selectedValues[0];
      getData(true);
    }
    // Picker 确认事件续写
    show[type] = false;
  }
  // 显示 Picker
  function showPicker(type) {
    show[type] = true;
  }
  // 优先级Mpa
  const priorityMap = {
    p0: 'P0',
    p1: 'P1',
    p2: 'P2',
    p3: 'P3',
  };
  const priorityTypeMap = {
    p0: '#D7000F',
    p1: '#FB9A0E',
    p2: '#3875ff',
    p3: '#36D399',
  };
  function getPriorityType(priority) {
    return priorityTypeMap[priority];
  }
  const bgColorMap = {
    未开始: '#f2f6fc',
    已解决: '#52C41A',
    解决中: '#3875FF',
    无需解决: '#FFC900',
    已关闭: '#262626',
    已回访: '#9254DE',
    待分发: '#FF7D27',
  };
  const ftColorMap = {
    未开始: '#989898',
    已解决: '#fff',
    解决中: '#fff',
    无需解决: '#fff',
    已关闭: '#fff',
    已回访: '#fff',
    待分发: '#fff',
  };
  function getColorStatus(status) {
    return bgColorMap[status] || 'status-default';
  }
  function getFtColorStatus(status) {
    return ftColorMap[status] || 'status-default';
  }
  /** 配置筛选组（自动绑定 state.filter 的 key） **/
  const filterGroups = computed(() => [
    {
      label: '工单状态',
      key: 'status',
      expanded: false,
      selected: state.filter.status,
      options: state.statusList || [],
    },
    {
      label: '工单类型',
      key: 'type',
      expanded: false,
      selected: state.filter.type,
      options: state.workTypeList || [],
    },
    {
      label: '优先级',
      key: 'priority',
      expanded: false,
      selected: state.filter.priority,
      options: state.priorityList || [],
    },

    {
      label: '问题来源',
      key: 'questionSource',
      expanded: false,
      selected: state.filter.questionSource,
      options: state.wtlyList || [],
    },
  ]);

  const maxVisible = 8;

  /** 选择切换（单选，可取消） **/
  function toggleTag(group, option) {
    group.selected = group.selected === option.value ? null : option.value;
    // 写入 state.filter
    state.filter[group.key] = group.selected;
    console.log('当前筛选条件：', state.filter);
  }

  function fatherCancel() {
    state.addOrEditVisible = false;
  }
  const handleSaved = () => {
    state.addOrEditVisible = false;
    // 这里刷新父页面数据
    getData();
  };
  function jumpDetail(id) {
    handleRedirect(`/pages/Page3000001011/Page3000001011?id=${id}`);
  }
</script>
<style lang="less" scoped>
  .page_root {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden !important;
    background-image: url('http://10.40.0.33:9001/file-storage/539771854764980224-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
  }
  .loading-text {
    text-align: center;
    padding: 20rpx;
    color: #999;
  }
  .main {
    height: calc(100vh - 300rpx); /* 75rpx + 55rpx */
    padding: 15rpx;
    margin-top: 0;
  }
  .loading-icon {
    height: 100rpx;
    width: 100rpx;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .gd-item {
    border: 1.5rpx solid #ffffff;
    border-radius: 12rpx;
    margin-bottom: 32rpx;
    background-color: #fff;
  }
  .gd-title {
    border-radius: 6rpx;
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
    margin-bottom: 8rpx;
  }
  .gd-content {
    background-image: url('http://10.40.0.33:9001/file-storage/539776956286449664-source.png');
    background-size: cover;
    background-position: center;
    border: 1.5rpx solid #ffffff;
    border-radius: 6rpx;
    padding: 24rpx;
  }
  .operatin-btn {
    background-color: #fff;
    opacity: 0.9;
    padding: 18rpx 24rpx 24rpx 24rpx;
  }
  .gd-top-icon {
    display: flex;
    gap: 8rpx;
    position: relative;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16rpx;
  }
  .title-left-icon {
    display: flex;
    gap: 16rpx;
    align-items: center;
    justify-content: start;
  }
  .gd-type {
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.65);
    font-weight: 400;
  }
  .title-right-icon {
    display: flex;
    flex: 1;
    justify-content: end;
    gap: 16rpx;
  }
  .time-out {
    width: 150rpx;
    height: 40rpx;
    border: 1rpx solid #d7000f;
    display: flex;
    font-size: 26rpx;
    line-height: 40rpx;
    justify-content: center;
    padding: 0 16rpx;
    border-radius: 8rpx;
    color: #d7000f;
  }
  .status-view {
    font-size: 28rpx;
    width: 150rpx;
    height: 40rpx;
    display: flex;
    text-align: center;
    justify-content: center;
    padding: 0 16rpx;
    border-radius: 8rpx;
  }
  .proority-view {
    width: 180rpx;
    height: 40rpx;
    color: #ffff;
    text-align: center;
    border-radius: 16px 2px 16px 2px;
  }

  .gd-msg {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16rpx;
  }
  .first-line {
    margin-bottom: 12rpx;
  }
  .second-line {
    margin-bottom: 18rpx;
  }

  .default-font,
  .bold-font {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
    letter-spacing: 0;
    flex-shrink: 0; /* 宽度固定不被压缩 */
  }
  .msg-item {
    margin: 3rpx 0;
    display: flex;
    align-items: center;
    gap: 8rpx;
    justify-content: start;
    flex-shrink: 0;
  }
  .warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .rect {
    color: #fff;
  }
  .popup-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  }

  .popup-header {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-weight: bold;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
    z-index: 10;
    position: relative;
  }
  .header-icon {
    position: absolute;
    right: 16rpx;
    top: 0;
  }

  .popup-body {
    flex: 1;
    overflow-y: auto;
    background-color: #fff;
    padding: 10rpx;
  }

  .popup-footer {
    padding: 10rpx;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    z-index: 10;
  }
  .container {
    position: relative;
    height: 100vh;
    display: flex;
    flex-direction: column;

    box-sizing: border-box;
  }

  :deep(.van-popup) {
    overflow: hidden;
  }
  .more-btn {
    color: #fff;
    font-size: 24rpx;
    line-height: 48rpx;
    display: flex;
    gap: 12rpx;
  }
  .filter-wrapper {
    position: relative;
    background-image: url('http://10.40.0.33:9001/file-storage/539771854764980224-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top center;
    height: 100%;
  }
  /* 滚动内容区域 */
  .form-body {
    margin-top: 50rpx;
    overflow-y: auto;
    padding: 32rpx 32rpx 80rpx 32rpx;
  }
  .top-title {
    text-align: center;
    padding: 10px 16px;
    height: 80rpx;
    font-size: 28rpx;
    font-weight: 600;
    border-bottom: 1px solid #d9d9d9;
  }
  /* 固定底部按钮栏 */
  .footer-bar {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    gap: 16rpx;
    padding: 16rpx;
    z-index: 10;

    .van-button {
      flex: 1;
    }
  }
  .page-title {
    display: flex;
    justify-content: space-between;
    padding: 10rpx;
    color: #fff;
    font-weight: 600;
    padding: 10rpx 16rpx;
    align-items: center;
  }
  .filter-header {
    margin-top: 16rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;
    margin-bottom: 24rpx;
    .toggle {
      font-size: 26rpx;
      color: #1989fa;
    }
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    overflow: hidden;
    transition: max-height 0.3s ease;
  }

  .tag-list.collapsed {
    max-height: 160rpx; // 默认显示两行
  }

  .tag {
    padding: 12rpx 24rpx;
    border-radius: 10rpx;
    background-color: #f4f4f4;
    font-size: 20rpx;
    color: #333;
    transition: all 0.2s;
    width: 160rpx;
    height: 64rpx;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.45);
    text-align: right;
    font-weight: 400;
    text-align: center;
  }

  .tag.active {
    background-color: #3366ff;
    color: #ffffff;
  }
  .filter-title {
    text-align: center;
    padding: 10px 16px;
    height: 80rpx;
    font-size: 28rpx;
    font-weight: 600;
    border-bottom: 1px solid #d9d9d9;
  }
  :deep(.van-dropdown-item__content) {
    overflow: auto;
  }
  // /*样式自定义*/

  .search-body {
    padding: 0 20rpx;
    display: flex;
    justify-content: space-between;
  }

  // 左右布局
  .filters-row {
    display: flex;
    align-items: center;
    padding: 56rpx 20rpx 18rpx 20rpx;
    gap: 12rpx;
  }

  /* 左侧组：包含两个卡片，靠左显示（默认） */
  .left-group {
    display: flex;
    gap: 12rpx; /* 两个下拉之间的间隔 */
    align-items: center;
    /* 不设置宽度，按内容大小占位，右侧元素会被推到右 */
  }

  /* 右侧组：放“更多”并靠右 */
  .right-group {
    margin-left: auto; /* 把右侧推到容器最右 */
    display: flex;
    align-items: center;
  }

  /* 通用卡片样式（每个独立下拉） */
  .dropdown-card {
    border-radius: 8rpx;
    overflow: hidden;
  }

  /* 更显紧凑的更多按钮：可以改小宽度，让它更像图标按钮 */
  .more-card {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    border-radius: 8rpx;
    gap: 4rpx;
    font-size: 28rpx;
    color: #000000;
    font-weight: 400;
  }
  .seatch-icon {
    width: 35rpx;
    height: 35rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/539783845382535168-source.png');
    background-size: cover;
  }

  /* 去掉内部bar默认灰背景 */
  .dropdown-card .van-dropdown-menu__bar {
    background-color: transparent;
    box-shadow: none;
    display: flex;
    align-items: center;
    padding-left: 12rpx;
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  .right-icon {
    background-image: url('http://10.40.0.33:9001/file-storage/539774097599838208-source.png');
    background-size: cover;
    height: 36rpx;
    width: 31rpx;
  }
  :deep(.u-input) {
    background-color: #fff;
  }
</style>
